package com.wispx.gateway.core.netty.processor;

import com.wispx.gateway.core.context.GatewayContext;
import com.wispx.gateway.core.filter.FilterChainFactory;
import com.wispx.gateway.core.helper.GatewayContextHelper;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

import static com.wispx.gateway.core.helper.GatewayResponseHelper.buildHttpResponse;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_GATEWAY;

@Slf4j
public class NettyCoreProcessor implements NettyProcessor {
    @Override
    public void process(ChannelHandlerContext ctx, FullHttpRequest request) {
        try {
            // GatewayContext
            GatewayContext gatewayContext = GatewayContextHelper.buildGatewayContext(ctx, request);
            // FilterChain
            FilterChainFactory.buildFilterChain(gatewayContext);
            // doFilter
            gatewayContext.doFilter();
        } catch (Exception e) {
            log.error("出现异常", e);
            doWriteAndRelease(ctx, request, buildHttpResponse(BAD_GATEWAY));
        }
    }

    private void doWriteAndRelease(ChannelHandlerContext ctx, FullHttpRequest request, FullHttpResponse httpResponse) {
        ctx.writeAndFlush(httpResponse)
                .addListener(ChannelFutureListener.CLOSE); // 发送响应后关闭通道
        ReferenceCountUtil.release(request); // 释放与请求相关联的资源
    }
}
